/**
 * QrCodeUtil.java
 * com.sftj.framework.util
 * Copyright (c) 2019, 北京科技有限公司版权所有.
*/

package com.sftz.framework.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

/**
 * 二维码工具
 * 
 * @author   朱晓川
 * @Date	 2019年2月22日 	 
 */
public class QrCodeUtil {

	private static final int BLACK = 0xFF000000;

	private static final int WHITE = 0xFFFFFFFF;

	/**
	 * 生成包含字符串信息的二维码图片
	 * 
	 * @param output 输出流
	 * @param content 二维码携带信息
	 * @param size 二维码图片大小
	 * @param format 二维码的格式
	 */
	public static boolean createQrCode(OutputStream output, String content, int size, String format)
			throws WriterException, IOException {
		Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix bm = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size, hints);

		BufferedImage image = toImage(bm);
		return ImageIO.write(image, format, output);
	}

	private static BufferedImage toImage(BitMatrix bm) {
		int width = bm.getWidth();
		int height = bm.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bm.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}

	/**
	 * 测试代码
	 * @throws WriterException 
	 */
	public static void main(String[] args) throws IOException, WriterException {
		createQrCode(new FileOutputStream(new File("f:\\qrcode.jpg")), "https://xcx.sktcm.cn/courseDetails?id=217",
				500, "JPEG");
	}

}
